package myzd.services.impl;


import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import libedge.domain.exceptions.GenericException;
import lombok.extern.slf4j.Slf4j;
import myzd.client.WeChatQiYeClient;
import myzd.client.domain.LoginTokenResponse;
import myzd.domain.response.Content;
import myzd.mapper.UserMapper;
import myzd.services.ClientService;
import myzd.services.CmsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WangLei
 * @since 2017.11.22
 */
@Component
@Slf4j
public class DefaultCmsServiceImpl implements CmsService {
  @Autowired
  private ClientService clientService;
  @Autowired
  private WeChatQiYeClient weChatQiYeClient;
  @Autowired
  private UserMapper userMapper;
  @Autowired
  private ObjectMapper objectMapper;


  public LoginTokenResponse userSsoLogin(String ssoLogin, String url) throws GenericException {
    LoginTokenResponse loginTokenResponse = new LoginTokenResponse();
    loginTokenResponse.setToken(ssoLogin + "?redirect_uri=" + url + "/api/v1/callback&state=crm");
    return loginTokenResponse;
  }


  @Override
  @Transactional(rollbackFor = GenericException.class)
  public ArrayList<Content> transformDetailsDtoList(List<Content> contentDetailsList) {
    ArrayList<Content> contentDetailsDtoList = new ArrayList<>();
    if (contentDetailsList == null || contentDetailsList.size() == 0) {
      return contentDetailsDtoList;
    }
    contentDetailsList.forEach(o -> {
      try {
        contentDetailsDtoList.add(transformDetailsToDto(o));
      } catch (GenericException e) {
        log.warn("GenericException", e);
      }
    });
    return contentDetailsDtoList;
  }

  @Transactional(rollbackFor = GenericException.class)
  public Content transformDetailsToDto(Content contentDetails) throws GenericException {
    Content contentDetailsDto = new Content();
    JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Content.class);
    if (contentDetailsDto == null) {
      return null;
    }
    try {
      BeanUtils.copyProperties(contentDetails, contentDetailsDto);
      return contentDetailsDto;
    } catch (Exception e) {
      log.warn("transformDetailsToDto", e);
      throw new GenericException("1318001", e.getMessage());
    }
  }
}
